package com.henghe.data_process.service;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.henghe.data_process.entity.*;
import com.henghe.data_process.mapper.*;
import com.henghe.frame.domain.base.BaseClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2025/5/29 16:48
 */
@Service
@Slf4j
public class CommonService extends BaseClass {

    @Autowired
    private TBdSupplierMapper tBdSupplierMapper;
    @Autowired
    private TBdSuppliergroupMapper tBdSuppliergroupMapper;
    @Autowired
    private TBdSuppliergroupdetailMapper tBdSuppliergroupdetailMapper;
    @Autowired
    private TBdSupplierlinkmanMapper tBdSupplierlinkmanMapper;
    @Autowired
    private TkXsw1Gysfllb01Mapper tkXsw1Gysfllb01Mapper;
    @Autowired
    private Tk02Mapper tk02Mapper;
    @Autowired
    private TSecBizpartneruserMapper tSecBizpartneruserMapper;
    @Autowired
    private TSecUserMapper tSecUserMapper;
    @Autowired
    private TBdSpgroupstandardMapper tBdSpgroupstandardMapper;

    public List getList() {
//        List<TBdSupplier> tBdSuppliers = tBdSupplierMapper.selectList(null);
//        List<TBdSuppliergroup> tBdSuppliergroups = tBdSuppliergroupMapper.selectList(null);
//        List<TBdSuppliergroupdetail> tBdSuppliergroupdetails = tBdSuppliergroupdetailMapper.selectList(null);
//        List<TBdSupplierlinkman> tBdSupplierlinkmen = tBdSupplierlinkmanMapper.selectList(null);
//        List<TkXsw1Gysfllb01> tkXsw1Gysfllb01s = tkXsw1Gysfllb01Mapper.selectList(null);
//        List<TSecBizpartneruser> tSecBizpartnerusers = tSecBizpartneruserMapper.selectList(null);
//        List<TSecUser> tSecUsers = tSecUserMapper.selectList(null);
        List<TBdSpgroupstandard> tBdSpgroupstandards = tBdSpgroupstandardMapper.selectList(new LambdaQueryWrapper<TBdSpgroupstandard>().eq(TBdSpgroupstandard::getFenable, "1"));
        return tBdSpgroupstandards;
    }

    public void update(TBdSupplier tBdSupplier) {
        tBdSupplier.setFadminorgid(1L);
        tBdSupplierMapper.updateById(tBdSupplier);
    }

    @Transactional
    public void importExcel2(List<ExcelObj2> excelObj2s) {
        Integer i = 1;
        for (ExcelObj2 excelObj2 : excelObj2s) {
            i++;
            TBdSupplier fnumber = tBdSupplierMapper.selectOne(new QueryWrapper<TBdSupplier>().eq("fnumber", excelObj2.getOldNo().trim()));
            if (fnumber == null) {
                System.out.println("第" + i + "行编码不存在");
            } else {
                fnumber.setFnumber(excelObj2.getNewNo());
                tBdSupplierMapper.updateById(fnumber);
            }
        }
    }


    public Object importExcel(List<ExcelObj> objects) {
        List<ErrorInfo> errorInfos = new ArrayList<>();
        Integer i = 4;
        List<TBdSupplier> list = new ArrayList<>();
        for (ExcelObj o : objects) {
            ErrorInfo errorInfo = new ErrorInfo();
            String e = "";
            i++;
            try {
                if (!StringUtils.isEmpty(o.getNo())) {
                    TBdSupplier s = tBdSupplierMapper.selectOne(new QueryWrapper<TBdSupplier>().eq("fnumber", o.getNo().trim()));
                    if (s == null) {
                        e += "第" + i + "行未查询到";
                        continue;
                    }
                    if (!StringUtils.isEmpty(o.getAddress()) && !StringUtils.isEmpty(o.getAddress().trim())) {
                        s.setFaddress(o.getAddress().trim());
                    }
                    if (!StringUtils.isEmpty(o.getLink()) && !StringUtils.isEmpty(o.getLink().trim())) {
                        String link = o.getLink().trim();
                        if (link.equals("是")) {
                            s.setFkXsw1Link("1");
                        } else if (link.equals("否")) {
                            s.setFkXsw1Link("0");
                        }
                    }
                    if (!StringUtils.isEmpty(o.getProperty()) && !StringUtils.isEmpty(o.getProperty().trim())) {
                        String p = o.getProperty().trim();
                        if ("直接供应商".equals(p)) {
                            s.setFkXsw1Businessproperty("1");
                        } else if ("代理商".equals(p)) {
                            s.setFkXsw1Businessproperty("2");
                        } else if ("贸易商".equals(p)) {
                            s.setFkXsw1Businessproperty("3");
                        }
                    }
                    if (!StringUtils.isEmpty(o.getProperty()) && !StringUtils.isEmpty(o.getProperty().trim())) {
                        s.setFkXsw1Businessproperty(o.getProperty().trim());
                    }
                    if (!StringUtils.isEmpty(o.getNumber()) && !StringUtils.isEmpty(o.getNumber().trim())) {
                        TkXsw1Gysfllb01 fnumber = tkXsw1Gysfllb01Mapper.selectOne(new QueryWrapper<TkXsw1Gysfllb01>().eq("fnumber", o.getNumber().trim()));
                        if (fnumber == null) {
//                        e+="第"+i+"行供应商标签（供货金额风险）.编码 未查询到";
                        } else {
                            s.setFkXsw1Basedatafield(fnumber.getFid());
                        }
                    }
                    if (!StringUtils.isEmpty(o.getNumber2()) && !StringUtils.isEmpty(o.getNumber2().trim())) {
                        Tk02 fnumber = tk02Mapper.selectOne(new QueryWrapper<Tk02>().eq("fnumber", o.getNumber2().trim()));
                        if (fnumber == null) {
//                        e+="第"+i+"行供应商标签（供货质量风险）.编码 未查询到";
                        } else {
                            s.setFkXsw1Basedatafield1(fnumber.getFid());
                        }
                    }

                    /**
                     * 处理联系人
                     */
                    if (!StringUtils.isEmpty(o.getName()) && !StringUtils.isEmpty(o.getName().trim())) {
                        List<TBdSupplierlinkman> tBdSupplierlinkmen = tBdSupplierlinkmanMapper.selectList(new QueryWrapper<TBdSupplierlinkman>().eq("fid", s.getFid())
                                .eq("fcontactperson", o.getName().trim()));
                        if (!tBdSupplierlinkmen.isEmpty()) {
                            TBdSupplierlinkman tBdSupplierlinkman = tBdSupplierlinkmen.get(0);
                            Boolean isUpdate = false;
                            if (!StringUtils.isEmpty(o.getPost()) && !StringUtils.isEmpty(o.getPost().trim())) {
                                isUpdate = true;
                                tBdSupplierlinkman.setFcontactpersonpost(o.getPost().trim());
                            }
                            if (!StringUtils.isEmpty(o.getZhcn()) && !StringUtils.isEmpty(o.getZhcn().trim())) {
                                isUpdate = true;
                                tBdSupplierlinkman.setFdept(o.getZhcn().trim());
                            }
                            if (!StringUtils.isEmpty(o.getPhone()) && !StringUtils.isEmpty(o.getPhone().trim())) {
                                isUpdate = true;
                                tBdSupplierlinkman.setFphone(o.getPhone().trim());
                            }
                            if (!StringUtils.isEmpty(o.getEmail()) && !StringUtils.isEmpty(o.getEmail().trim())) {
                                isUpdate = true;
                                tBdSupplierlinkman.setFemail(o.getEmail().trim());
                            }
                            if (isUpdate) {
                                tBdSupplierlinkmanMapper.updateById(tBdSupplierlinkman);
                            }
                        } else {
                            System.out.println(o.getNo() + "  第" + i + "行联系人信息匹配不上  ===>" + o.getName());
                        }
                    }
                    if (!StringUtils.isEmpty(o.getNumber4()) && !StringUtils.isEmpty(o.getNumber4().trim())) {
                        List<TBdSuppliergroupdetail> fsupplierid = tBdSuppliergroupdetailMapper.selectList(new QueryWrapper<TBdSuppliergroupdetail>().eq("fsupplierid", s.getFid()));
                        if (fsupplierid.isEmpty()) {
                            e += "第" + i + "行未查询到对应的分类标准";
                        } else {
                            TBdSuppliergroupdetail tBdSuppliergroupdetail = null;
                            for (TBdSuppliergroupdetail tbgd : fsupplierid) {
                                if (tbgd.getFstandardid() != null) {
                                    TBdSpgroupstandard tBdSpgroupstandard = tBdSpgroupstandardMapper.selectById(tbgd.getFstandardid());
                                    if (tBdSpgroupstandard != null &&
                                            !StringUtils.isEmpty(tBdSpgroupstandard.getFenable()) &&
                                            tBdSpgroupstandard.getFenable().equals("1")) {
                                        tBdSuppliergroupdetail = tbgd;
                                        break;
                                    }
                                }
                            }
                            if (tBdSuppliergroupdetail == null) {
                                System.out.println("第" + i + "行，未找到对应的启用的供应商分类标准，取第0个进行赋值");
                                tBdSuppliergroupdetail = fsupplierid.get(0);
                            }
                            if (tBdSuppliergroupdetail == null) {
                                e += "第" + i + "行未查询到对应的分类标准";
                            } else {
                                TBdSuppliergroup fnumber = tBdSuppliergroupMapper.selectOne(new QueryWrapper<TBdSuppliergroup>().eq("fnumber", o.getNumber4().trim()));
                                if (fnumber == null) {
                                    e += "第" + i + "行分类标准未查询到";
                                } else {
                                    tBdSuppliergroupdetail.setFgroupid(fnumber.getFid());
                                    tBdSuppliergroupdetailMapper.updateById(tBdSuppliergroupdetail);
                                }
                            }
                        }
                    }
                    s.setFstatus("B");
                    if (StringUtils.isEmpty(e)) {
                        list.add(s);
//                    tBdSupplierMapper.updateById(s);
                    }

                } else {
                    e += "第" + i + "行编码不能为空;";
                    continue;
                }
                errorInfo.setNumber(Long.valueOf(i));
                errorInfo.setMessage(e);
                errorInfos.add(errorInfo);

            } catch (Exception exception) {
                exception.printStackTrace();
                System.err.println(i + "行" + o.getNo());
                continue;
            }
        }
        if (!list.isEmpty())
            list.forEach(e -> tBdSupplierMapper.updateById(e));
        return errorInfos;
    }

    public void updateStatus() {
        List<TBdSupplier> tBdSuppliers = tBdSupplierMapper.selectList(new QueryWrapper<TBdSupplier>().eq("fstatus", "A"));
        for (TBdSupplier t : tBdSuppliers) {
            List<TBdSuppliergroupdetail> fsupplierid = tBdSuppliergroupdetailMapper.selectList(new QueryWrapper<TBdSuppliergroupdetail>().eq("fsupplierid", t.getFid()));
            if (!fsupplierid.isEmpty()) {
                TBdSuppliergroupdetail tBdSuppliergroupdetail = fsupplierid.get(0);
                TBdSuppliergroup fnumber = tBdSuppliergroupMapper.selectOne(new QueryWrapper<TBdSuppliergroup>().eq("fnumber", "QTGYS"));
                if (fnumber != null) {
                    tBdSuppliergroupdetail.setFgroupid(fnumber.getFid());
                    tBdSuppliergroupdetailMapper.updateById(tBdSuppliergroupdetail);
                }
            }
        }
    }

    public void handleData() {
        QueryWrapper<TBdSupplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.last(" where length(fnumber) = 10 and fnumber like 'Sup-%'");
        List<TBdSupplier> fnumber = tBdSupplierMapper.selectList(queryWrapper);
        if (fnumber.isEmpty()) {
            System.out.println("查询sep like为空");
            return;
        }
        List<String> collect = fnumber.stream().filter(e -> !StringUtils.isEmpty(e.getFnumber()))
                .map(TBdSupplier::getFnumber)
                .map(e -> e.replace("Sup-", ""))
                .collect(Collectors.toList());
        collect.sort(Comparator.comparingLong(Long::parseLong));
        collect = collect.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
        String max = collect.get(0);
        long l = Long.parseLong(max);
        QueryWrapper<TBdSupplier> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.last(" where length(fnumber) <> 10 or fnumber not like 'Sup-%'");
        List<TBdSupplier> handleList = tBdSupplierMapper.selectList(queryWrapper2);
        if (handleList.isEmpty()) {
            System.out.println("查询sep not like为空");
            return;
        }
        for (TBdSupplier tBdSupplier : handleList) {
            l++;
            String f = "Sup-" + handleNumber(l);
            System.out.println("修改" + tBdSupplier.getFnumber() + "成" + f);
            tBdSupplier.setFnumber(f);
            tBdSupplierMapper.updateById(tBdSupplier);
        }
    }

    public List<TBdSupplier> getTest() {
        QueryWrapper<TBdSupplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.last(" where length(fnumber) <> 10 or fnumber not like 'Sup-%'");
//        queryWrapper.apply("length({0}) = 10", "fnumber");
//        queryWrapper.likeRight("fnumber","Sup-");
        return tBdSupplierMapper.selectList(queryWrapper);
    }

    public void handleDataOut() {
//        QueryWrapper<TBdSupplier> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("fnumber","Sup-002659");
//        handleData2(tBdSupplierMapper.selectOne(queryWrapper));
        handleData2(null);
    }

    public void handleData2(TBdSupplier supplier) {
        System.out.println("开始执行");
        Integer cnt = 0;
        if (supplier == null) {
            List<TBdSupplier> tBdSuppliers = tBdSupplierMapper.selectList(null);
            for (TBdSupplier t : tBdSuppliers) {
                List<TBdSupplierlinkman> men = tBdSupplierlinkmanMapper.selectList(new QueryWrapper<TBdSupplierlinkman>().eq("fid", t.getFid()));
                if (men.isEmpty())
                    continue;
                List<TSecBizpartneruser> usersUnion = tSecBizpartneruserMapper.selectList(new LambdaQueryWrapper<TSecBizpartneruser>()
                        .eq(TSecBizpartneruser::getFbizpartnerid, t.getFbizpartnerid()));
                for (TSecBizpartneruser e : usersUnion) {
                    if (e.getFuserid() != null) {
                        TSecUser user = tSecUserMapper.selectOne(new QueryWrapper<TSecUser>().eq("fid", e.getFuserid()));
                        if (user != null && !com.henghe.frame.common.util.StringUtils.isEmpty(user.getFtruename())) {
                            TBdSupplierlinkman tBdSupplierlinkman = men.stream().filter(a -> !StringUtils.isEmpty(a.getFcontactperson()) && a.getFcontactperson().equals(user.getFtruename())).findAny().orElse(null);
                            if (tBdSupplierlinkman != null) {
                                Boolean isUpdate = false;
                                if (!StringUtils.isEmpty(tBdSupplierlinkman.getFphone())) {
                                    user.setFphone(tBdSupplierlinkman.getFphone());
                                    isUpdate = true;
                                }
                                if (!StringUtils.isEmpty(tBdSupplierlinkman.getFemail())) {
                                    user.setFemail(tBdSupplierlinkman.getFemail());
                                    isUpdate = true;
                                }
                                if (isUpdate) {
                                    tSecUserMapper.updateById(user);
                                    cnt++;
                                    System.out.println("执行了" + cnt + "个," + user.getFtruename() + " 供应商编号：" + t.getFnumber());
                                }
                            }
                        } else {
                            System.out.println(t.getFnumber() + "  " + e.getFuserid() + " 用户不存在");
                        }
                    }
                }
            }
        } else {
            List<TBdSupplierlinkman> men = tBdSupplierlinkmanMapper.selectList(new QueryWrapper<TBdSupplierlinkman>().eq("fid", supplier.getFid()));
            if (men.isEmpty())
                return;
            List<TSecBizpartneruser> usersUnion = tSecBizpartneruserMapper.selectList(new LambdaQueryWrapper<TSecBizpartneruser>()
                    .eq(TSecBizpartneruser::getFbizpartnerid, supplier.getFbizpartnerid()));
            for (TSecBizpartneruser e : usersUnion) {
                if (e.getFuserid() != null) {
                    TSecUser user = tSecUserMapper.selectOne(new QueryWrapper<TSecUser>().eq("fid", e.getFuserid()));
                    if (user != null && !com.henghe.frame.common.util.StringUtils.isEmpty(user.getFtruename())) {
                        TBdSupplierlinkman tBdSupplierlinkman = men.stream().filter(a -> !StringUtils.isEmpty(a.getFcontactperson()) && a.getFcontactperson().equals(user.getFtruename())).findAny().orElse(null);
                        if (tBdSupplierlinkman != null) {
                            Boolean isUpdate = false;
                            if (!StringUtils.isEmpty(tBdSupplierlinkman.getFphone())) {
                                user.setFphone(tBdSupplierlinkman.getFphone());
                                isUpdate = true;
                            }
                            if (!StringUtils.isEmpty(tBdSupplierlinkman.getFemail())) {
                                user.setFemail(tBdSupplierlinkman.getFemail());
                                isUpdate = true;
                            }
                            if (isUpdate) {
                                tSecUserMapper.updateById(user);
                            }
                        }
                    } else {
                        System.out.println(supplier.getFnumber() + "  " + e.getFuserid() + " 用户不存在");
                    }
                }
            }
        }
        System.out.println("执行结束");
    }

    private static String handleNumber(Long num) {
        return String.format("%06d", num);
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("001024", "010240", "001023");
        list.sort(Comparator.comparingLong(Long::parseLong));
        list = list.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
        System.out.println(list);
        String s = list.get(0);
        List<String> list1 = Arrays.asList("1", "2", "3");
        List<String> list2 = new ArrayList<>();
        System.out.println(handleNumber(Long.parseLong(s) + 1));
        long l = Long.parseLong(s);
        for (String s1 : list1) {
            l++;
            list2.add(handleNumber(l));
        }
        System.out.println(list2);
    }
}
